package qj.concurrent;

import java.text.NumberFormat;

/**
 * This has to public as the thread will go around.
 * This stand for a concurrent, who is managed by the ServantManager
 * Created by QuanLA
 * Date: Mar 15, 2006
 * Time: 9:59:46 AM
 */
public class ServantThread extends Thread {
    private static int count;

    private ServantTask task;
    private boolean free;
    private ServantManager myManager;

    // Format the Thread name
    private static final NumberFormat nf = NumberFormat.getInstance();
    static {
        nf.setMinimumIntegerDigits(3);
    }

    /**
     * Constructor
     * @param manager
     */
    ServantThread(ServantManager manager) {
        super("T" + nf.format(++count));
        if (count==999) count = 0;
        this.myManager = manager;
    }

    /**
     *
     * @return the task being hold
     */
    public ServantTask getCurrentTask() {
        return task;
    }

    /**
     * Set the task to be done
     * @param task
     */
    public synchronized void setTask(ServantTask task) {
        this.task = task;
    }

    /**
     * Wake the thread up and end it.
     */
    public synchronized void kill() {
        free = true;
        notify();
    }

    /**
     *
     */
    public void run() {
        while (!free) {
            if (task!=null) {
                synchronized (this) {
                    try {
                        Servant.serveTask(task);
                    } finally {
                        myManager.doneTask(this);
                    }
                }
            }

            // When announce done task with manager, the thread may be assign another task
            if (task==null) {
                synchronized (this) {
                    try {
                        wait(500);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
    }
}
